import 'package:fish_redux/fish_redux.dart';
import 'package:kunlun_gas/app_files.dart';
import 'package:kunlun_gas/PublicSource/utils/bluetooth_helper.dart';
import 'action.dart';
import 'state.dart';

Effect<BlueToothSaveViewState> buildEffect() {
  return combineEffects(<Object, Effect<BlueToothSaveViewState>>{
    BlueToothSaveViewAction.action: _onAction,
    BlueToothSaveViewAction.onSubmit: _onSubmit,
    Lifecycle.initState: _initState,
  });
}

void _onAction(Action action, Context<BlueToothSaveViewState> ctx) {}

void _initState(Action action, Context<BlueToothSaveViewState> ctx) async {
  if (ctx.state.model.ctrlCode.contains('QC')) {
    ResultData res = await CommonNetWork.getCardMemo(ctx.state.model.userID);
    if (res.success) {
      ctx.state.cardMemo = res.data;
    } else {
      await CommonUtils.showAlertView(ctx.context, res.desc);
      Navigator.pop(ctx.context);
    }
    return;
  }
  ResultData res = await CommonNetWork.getCardMemo(ctx.state.model.userID);
  if (res.success) {
    ctx.state.cardMemo = res.data;
  } else {
    await CommonUtils.showAlertView(ctx.context, res.desc);
    Navigator.pop(ctx.context);
  }
}

void _onSubmit(Action action, Context<BlueToothSaveViewState> ctx) async {
  // print(ctx.state.cardMemo);
  bool res = await BlueToothHelper.saveGas(
    ctx.context,
    sn: ctx.state.bluetoothNo,
    orderID: ctx.state.model.orderID,
    userNo: ctx.state.model.accountNo,
    cardNo: ctx.state.model.cardNo,
    cardGas: double.tryParse(ctx.state.model.orderGas).toStringAsFixed(0),
    ctrlCode: ctx.state.model.ctrlCode,
    cardMemo: ctx.state.cardMemo,
  );
  if (res == true) {
    bus.emit('refreshOrderList');
    Navigator.pop(ctx.context);
    Navigator.pop(ctx.context);
  }
}
